package com.bw.controller;

import com.alibaba.excel.EasyExcel;
import com.bw.entity.Bing;
import com.bw.entity.UserGroup;
import com.bw.entity.Zxt;
import com.bw.mapper.TuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class TuController {
    @Autowired
    TuMapper tuMapper;


    /**
     * 首页
     * @return
     */
    @RequestMapping("tu.do")
    public String tu(Model model) {
        // 下拉框 渲染
       List<UserGroup> groupList = tuMapper.selectGroup();

       model.addAttribute("groupList",groupList);
        return "tu";
    }

    /**
     * 点击展示 折线图/柱状图 的数据
     * @return
     */
    @RequestMapping("zxt.do")
    @ResponseBody
    public List<Zxt> zxt(Integer groupId) {

        return tuMapper.zxt(groupId);
    }
    /**
     * 点击展示 饼图 的数据
     * @return
     */
    @RequestMapping("bing.do")
    @ResponseBody
    public List<Bing> bing(Integer groupId) {

        return tuMapper.bing(groupId);
    }


    /**
     * 点击导出Excel
     * @return
     */
    @RequestMapping("excel.do")
    public void excel(Integer groupId, HttpServletResponse response) throws IOException {
        // 准备Excel 需要的数据
        List<Zxt> list = tuMapper.zxt(groupId);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("文件名字——01", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Zxt.class).sheet("sheet页的名字").doWrite(list);
    }
}
